package homework.no_2;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileWriter;
import java.io.IOException;

/**
 * 2.使用DOM解析第1题作业中编写的XML文档，输出所有学员信息，
 * 并进行以下操作：删除id为1的学生成绩信息，修改id为2的成绩为60，添加一个学生的成绩信息（id为5）。
 */
public class DOMStudents {
    private static final String PATH = "src/main/java/homework/no_2/Score2.xml";
    private static Document doc = null;
    static {
        //解析工厂对象
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            //获得解析器对象
            DocumentBuilder builder = factory.newDocumentBuilder();
            //获得文档对象
            doc = builder.parse(PATH);

        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void showInfo(){
        NodeList student = doc.getElementsByTagName("student");
        for (int i = 0; i < student.getLength(); i++) {
            Node node = student.item(i);
            Element eleStu = (Element)node;
            System.out.println(eleStu.getAttribute("id"));
            NodeList childNodes = eleStu.getChildNodes();
            for (int j = 0; j < childNodes.getLength(); j++) {
                Node node1 = childNodes.item(j);
                if (node1.getNodeType() == Node.ELEMENT_NODE){
                    System.out.println("\t"+node1.getFirstChild().getNodeValue());
                }
            }
        }
    }

    public static void saveXML(String path){
        TransformerFactory factory = TransformerFactory.newInstance();
        factory.setAttribute("indent-number",4);
        try {
            Transformer transformer = factory.newTransformer();
            transformer.setOutputProperty(OutputKeys.ENCODING,"utf-8");
            transformer.setOutputProperty(OutputKeys.INDENT,"yes");
            transformer.transform(new DOMSource(doc),new StreamResult(new FileWriter(path)));
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }


    public static void delete(){
        NodeList student = doc.getElementsByTagName("student");
        for (int i = 0; i < student.getLength(); i++) {
            Node item = student.item(i);
            Element eleID = (Element)student.item(i);
            if (eleID.getAttribute("id").equals("1")){

                NodeList childNodes = eleID.getChildNodes();//拿到所有字节点
                for (int j = 0; j < childNodes.getLength(); j++) {
                    Node eleS = childNodes.item(j);
                    if ((eleS.getNodeType() == Node.ELEMENT_NODE) && eleS.getNodeName().equals("score")){
                        item.removeChild(eleS);
                    }
                }
            }
        }
        saveXML(PATH);
    }

    public static void update() {
        NodeList scoreNode = doc.getElementsByTagName("score");
        Element eleScore = (Element)scoreNode.item(1);
        eleScore.setTextContent("60");
        saveXML(PATH);
    }

    public static void add(){
        Element element = doc.createElement("student");
        element.setAttribute("id","5");

        Element element1 = doc.createElement("score");
        element1.setTextContent("99");
        element.appendChild(element1);
        doc.getElementsByTagName("scores").item(0).appendChild(element);
        saveXML(PATH);

    }

    public static void main(String[] args) {
//        showInfo();
//        System.out.println("-----------------------");
        delete();
        update();

        add();
        showInfo();
    }
}
